use SRISK_all_countries_monthly.dta, clear

gen insample = 0
by NAME_RR time_RR: replace insample = 1 if _n == _N & _merge != 1

xtset cntyid yyyymm
tssmooth ma SRISK_TAK_6mo_ma = SRISK_TAK, window(5 1 0)
tssmooth ma SRISK_6mo_ma = SRISK, window(5 1 0)
tssmooth ma TA_6mo_ma = TA, window(5 1 0)

tssmooth ma T_SRISK_TAK_leaveout_6mo_ma = T_SRISK_TAK_leaveout, window(5 1 0)

gen SRISK_TAK_6mo_ma2 = SRISK_6mo_ma / (TA_6mo_ma * k)

gen SRISK_TAK_ma_ratio = SRISK_TAK_6mo_ma / SRISK_TAK_6mo_ma2

sum SRISK_TAK_ma_ratio, detail

gen gam1 = SRISK_TAK_ma_ratio
sort cntyid time_RR yyyymm

by cntyid time_RR: gen gam_temp = gam1 if _n == _N
by cntyid time_RR: egen gam2 = total(gam_temp), missing

drop gam_temp

sort cntyid yyyymm
gen SRISK_TAK_diff = (SRISK_TAK_6mo_ma - L6.SRISK_TAK_6mo_ma)
gen SRISK_TAK_avg_diff = (SRISK_TAK_avg - L6.SRISK_TAK_avg)

gen T_SRISK_TAK_leaveout_diff = (T_SRISK_TAK_leaveout_6mo_ma - L6.T_SRISK_TAK_leaveout_6mo_ma)
gen T_SRISK_TAK_leaveout_avg_diff = (T_SRISK_TAK_leaveout_avg - L6.T_SRISK_TAK_leaveout_avg)

gen SRISK_TAK_original = SRISK_TAK_6mo_ma
replace SRISK_TAK = SRISK_TAK_avg

gen SRISK_TAK_diff_original = SRISK_TAK_diff
replace SRISK_TAK_diff = SRISK_TAK_avg_diff

gen T_SRISK_TAK_leaveout_original = T_SRISK_TAK_leaveout_6mo_ma
replace T_SRISK_TAK_leaveout = T_SRISK_TAK_leaveout_avg

gen T_SRISK_TAK_leaveout_diff_orig = T_SRISK_TAK_leaveout_diff
replace T_SRISK_TAK_leaveout_diff = T_SRISK_TAK_leaveout_avg_diff

tab cntyid, gen(cntydummy)
eststo tobdom: qui tobit CRISIS SRISK_TAK SRISK_TAK_diff cntydummy* if insample == 1, ll(0) noconstant
matrix list e(b)
matrix b=e(b)
scalar sigma= sqrt(_b[/var(e.CRISIS)])
scalar b1 = _b[SRISK_TAK]
scalar b2 = _b[SRISK_TAK_diff]
scalar list b1 b2 sigma

predict ystarhat if insample == 1 
predict yhat if insample == 1, ystar(0,.) 
sum ystarhat, detail
sum yhat, detail

eststo tobglo: qui tobit CRISIS SRISK_TAK T_SRISK_TAK_leaveout T_SRISK_TAK_leaveout_diff cntydummy* if insample == 1, ll(0) noconstant
matrix list e(b)
matrix b_global=e(b)
scalar sigma_global= sqrt(_b[/var(e.CRISIS)])
scalar b1_global = _b[SRISK_TAK]
scalar list b1_global sigma_global

predict ystarhat_global if insample == 1 
predict yhat_global if insample == 1, ystar(0,.) 
sum ystarhat_global, detail
sum yhat_global, detail

replace SRISK_TAK = SRISK_TAK_original
replace SRISK_TAK_diff = SRISK_TAK_diff_original

replace T_SRISK_TAK_leaveout = T_SRISK_TAK_leaveout_original
replace T_SRISK_TAK_leaveout_diff = T_SRISK_TAK_leaveout_diff_orig

estimates restore tobdom
predict crisispr, pr(4,.)
predict xb

gen capacity = (4 - xb) / (b1 + b2) * TA_6mo_ma * k * gam2 + SRISK_6mo_ma

estimates restore tobglo

predict crisispr_global, pr(4,.)
predict xb_global

gen capacity_global = (4 - xb_global) / b1_global * TA_6mo_ma * k * gam2 + SRISK_6mo_ma
